<?php
/**
 * Created by PhpStorm.
 * User: peter
 * Date: 2018/7/12
 * Time: 下午10:00
 */

namespace app\admin\logic;


use app\model\OrderProcess;
use app\model\WeChat;
use extend\Functions;
use extend\STATUS_CODE;
use extend\WeChatTemplateMessage;

class Order
{
    /**
     * @purpose 发货
     * @param array $data
     * @param int $administrator_id
     * @return array
     * @throws \EasyWeChat\Kernel\Exceptions\HttpException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public static function deliverGoods (array $data, int $administrator_id): array
    {
        if (!isset($data['id']) || !$data['id']) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '参数错误!'
            );
        }
        if (!isset($data['express_company']) || !$data['express_company']) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '参数错误!'
            );
        }
        if (!isset($data['express_code']) || !$data['express_code']) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '参数错误!'
            );
        }
        if (!isset($data['express_no']) || !$data['express_no']) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '缺少快递单号!'
            );
        }
        $order = new \app\model\Order();
        $order_process  = new OrderProcess();
        $order->startTrans();
        $order_status = $order
            ->lock(true)
            ->where('id', $data['id'])
            ->value('status');
        if ($order_status !== 2) {
            return Functions::result(
                STATUS_CODE::FAIL,
                '订单状态错误!'
            );
        }
        // 构建订单数据
        $order_data   = [];
        $order_data['status'] = 3;
        $order_data['express_company']  = $data['express_company'];
        $order_data['express_no']       = $data['express_no'];
        $order_data['express_code']     = $data['express_code'];
        // 构建订单流程数据
        $order_process_data = [];
        $order_process_data['order_id'] = $data['id'];
        $order_process_data['status']   = 3;
        $order_process_data['operator_type'] = 2;
        $order_process_data['operator_id'] = $administrator_id;
        $order_process_data['description'] = '商品已发货';

        $order_info = $order
            ->with('attach')
            ->field('id,uid,address,contacts,contacts_mobile')
            ->where('id', $data['id'])
            ->find();
        $message = [];
        $message['goods_title'] = '';
        foreach ($order_info->attach as $goods) {
            $message['goods_title'] .= $goods['title'].'['.$goods['spec'].'];';
        }
        $wechat                     =   new WeChat();
        $message['openid']          = $wechat->where('uid', $order_info->uid)->value('openid');
        $message['time']            = time();
        $message['express_company'] = $data['express_company'];
        $message['express_no']      = $data['express_no'];
        $message['address']         = $order_info->address.'['.$order_info->contacts.' '.$order_info->contacts_mobile.']';
        $order_result = $order
            ->save($order_data, ['id' => $data['id']]);
        $order_process_result = $order_process
            ->data($order_process_data)
            ->save();
        // 订阅快递100
        $result_express     = Express::subscribe([
            'company'   => $data['express_code'],
            'number'    => $data['express_no'],
            'to'        => $order_info->address
        ]);
        if (intval($result_express['returnCode']) !== 200) {
            $order->rollback();
            return Functions::result(
                STATUS_CODE::FAIL,
                '物流快递订阅失败, 失败原因: ['.$result_express['returnCode'].']['.$result_express['message'].']'
            );
        }
        if ($order_result && $order_process_result) {
            /**
             * @param array $data = [
             *  'openid' => '',
             *  'goods_title' => '',
             *  'time' => '',
             *  'express_company' => '',
             *  'express_no' => '',
             *  'address' => '',
             * ]
             */
            WeChatTemplateMessage::deliverGoods($message);
            $order->commit();
            return Functions::result(
                STATUS_CODE::SUCCESS,
                '发货成功!'
            );
        }
        $order->rollback();
        return Functions::result(
            STATUS_CODE::FAIL,
            '发货失败'
        );

    }
    /**
     * @purpose 获取订单列表
     * @param array $where
     * @param int $page
     * @param int $size
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function items (
        array $where = [],
        int $page = 1,
        int $size = 40,
        string $kw,
        int $search_type
        ): array
    {
        $order      =   new \app\model\Order();
        $fields     =   'id,uid,status,order_no,FROM_UNIXTIME(pay_time, \'%Y-%m-%d %H:%i:%s\') as pay_date,pay_type,pay_no,pay_money,address,message,contacts,contacts_mobile,express_company,express_no,is_distribution,cancel_reason,FROM_UNIXTIME(create_at, \'%Y-%m-%d %H:%i:%s\') as create_time';
        switch ($search_type) {
            case 1:
                break;
            case 2:
                break;
            case 3:
                break;
        }
        $result     =   $order
            ->with('asMember')
            ->where($where)
            ->field($fields)
            ->page($page, $size)
            ->order('create_at desc')
            ->select();
        $total      = $order->total($where);
        return Functions::result(
            STATUS_CODE::SUCCESS,
            [
                'total' => $total,
                'list'  => $result
            ]
        );
    }

    /**
     * @purpose 通过ID获取订单详情
     * @param int $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function detailById (int $id): array
    {
        $fields     =   'id,uid,status,order_no,FROM_UNIXTIME(pay_time, \'%Y-%m-%d %H:%i:%s\') as pay_date,pay_type,pay_no,pay_money,address,message,contacts,contacts_mobile,express_company,express_no,is_distribution,cancel_reason,FROM_UNIXTIME(create_at, \'%Y-%m-%d %H:%i:%s\') as create_time';
        $order      =   new \app\model\Order();
        $result     =   $order
            ->with('attach,asMember')
            ->where('id', $id)
            ->field($fields)
            ->find();
        return Functions::result(
            STATUS_CODE::SUCCESS,
            $result
        );
    }
}